package fule.com.playandroidkotlin.ui.api

import android.util.Log
import fule.com.playandroidkotlin.base.App.Companion.context
import fule.com.playandroidkotlin.ui.api.cookie.CookiesManager
import fule.com.playandroidkotlin.ui.util.AppConstant
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.ResponseBody
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.util.concurrent.TimeUnit

/**
 * 作者： ch
 * 时间： 2016/12/27.13:56
 * 描述：
 * 来源：
 */
class ApiRetrofit {
    private val retrofit: Retrofit
    private val client: OkHttpClient
    val apiService: ApiServer
    private val TAG = "ApiRetrofit"

    /**
     * 请求访问quest
     * response拦截器
     */
    private val interceptor = Interceptor { chain ->
        val request = chain.request()
        val startTime = System.currentTimeMillis()
        val response = chain.proceed(chain.request())
        val endTime = System.currentTimeMillis()
        val duration = endTime - startTime
        val mediaType = response.body()!!.contentType()
        val content = response.body()!!.string()
        Log.e(TAG, "----------Request Start----------------")
        Log.e(TAG, "| " + request.toString() + request.headers().toString())
        Log.e(TAG, "| Response:$content")
        Log.e(TAG, "----------Request End:" + duration + "毫秒----------")
        response.newBuilder()
                .body(ResponseBody.create(mediaType, content))
                .build()
    }
    private val headInterceptor = Interceptor { chain ->
        var request = chain.request()

        //获取到方法
        val method = request.method()
        if (method == "GET") {
            val httpUrlurl = request.url()
            val url = httpUrlurl.toString()
            val index = url.indexOf("?")
            if (index > 0) {
                //url = url + "&APP_KEY=" + AppConstant.APP_KEY;
            } else {
                //  url = url + "?APP_KEY=" + AppConstant.APP_KEY;  //拼接新的url
            }
            request = request.newBuilder().url(url).build() //重新构建请求
        } else if (method == "POST") {
            val requestBuilder = request.newBuilder()

            //请求体定制：统一添加token参数
            if (request.body()!!.contentLength() == 0L) {
                //没有参数
                val newFormBody = FormBody.Builder()
                //newFormBody.add("APP_KEY", AppConstant.APP_KEY);
                //newFormBody.add("APP_TOKEN", UserImpl.getAppToken());
                //newFormBody.add("version", AppUtils.getVersionName(App.getInstance()));
                requestBuilder.method(request.method(), newFormBody.build())
            } else if (request.body() is FormBody) {
                //正常post
                val newFormBody = FormBody.Builder()
                val oidFormBody = request.body() as FormBody?
                for (i in 0 until oidFormBody!!.size()) {
                    newFormBody.addEncoded(oidFormBody.encodedName(i), oidFormBody.encodedValue(i))
                }
                //newFormBody.add("APP_KEY", AppConstant.APP_KEY);
                // newFormBody.add("APP_TOKEN", UserImpl.getAppToken());
                // newFormBody.add("version", AppUtils.getVersionName(App.getInstance()));
                requestBuilder.method(request.method(), newFormBody.build())
            }
            //                else if (request.body() instanceof MultipartBody) {
//                    //包含图片
//                    MultipartBody oldBodyMultipart = (MultipartBody) request.body();
//
//                    List<MultipartBody.Part> oldPartList = oldBodyMultipart.parts();
//
//                    MultipartBody.Builder builder = new MultipartBody.Builder();
//                    builder.setType(MultipartBody.FORM);
//
//
//                    for (MultipartBody.Part part : oldPartList) {
//                        builder.addPart(part);
//                    }
//
//
////                    RequestBody appkey = RequestBody.create(MediaType.parse("multipart/form-data"), AppConstant.APP_KEY);
////                    RequestBody apptoken = RequestBody.create(MediaType.parse("multipart/form-data"), UserImpl.getAppToken());
//////                    MultipartBody.Part appkey = MultipartBody.Part.createFormData("APP_KEY", AppConstant.APP_KEY);
////                    MultipartBody.Part apptoken1 = MultipartBody.Part.createFormData("APP_TOKEN", "", apptoken);
////
////                    MultipartBody.Part appkey1 = MultipartBody.Part.createFormData("APP_KEY", "", appkey);
////
//////
////                    builder.addPart(appkey1);
////                    builder.addPart(apptoken1);
//                    builder.addPart(MultipartBody.Part.createFormData("APP_KEY", AppConstant.APP_KEY));
//                    builder.addPart(MultipartBody.Part.createFormData("APP_TOKEN", UserImpl.getAppToken()));
//
////                    builder.addFormDataPart("APP_KEY", AppConstant.APP_KEY);
////                    builder.addFormDataPart("APP_TOKEN", UserImpl.getAppToken());
//                    requestBuilder.put(builder.build());
//                }
            request = requestBuilder.build()
        }
        chain.proceed(request)

//            Request.Builder builder = request.newBuilder().addHeader("LEDAYOUXUAN", "159357456")
//                    .addHeader("APP_TOKEN", UserImpl.getAppToken());
//
//            return chain.proceed(builder.build());
    }

    companion object {
        private var apiRetrofit: ApiRetrofit? = null

        @JvmStatic
        val instance: ApiRetrofit?
            get() {
                if (apiRetrofit == null) {
                    synchronized(Any::class.java) {
                        if (apiRetrofit == null) {
                            apiRetrofit = ApiRetrofit()
                        }
                    }
                }
                return apiRetrofit
            }
    }

    init {
        client = OkHttpClient.Builder() //添加log拦截器
                .addInterceptor(interceptor)
                .addInterceptor(headInterceptor)
                .cookieJar(CookiesManager(context))
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS) //                .sslSocketFactory()
                .build()
        retrofit = Retrofit.Builder()
                .baseUrl(AppConstant.BASE_SERVER_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(ScalarsConverterFactory.create()) //支持RxJava2
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(client)
                .build()
        apiService = retrofit.create(ApiServer::class.java)
    }
}